package com.lj.queue.handler;

import cn.hutool.core.util.ClassUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.Iterator;

/**
 * @author luojing
 * @since 2025/7/17 10:18
 */
@Slf4j
public class DelayHandlerChain {

    private final Iterator<DelayMessageHandler<Object>> handlerIterator;

    public DelayHandlerChain(Collection<DelayMessageHandler<Object>> handlerList) {
        this.handlerIterator = handlerList.iterator();
    }

    public void next(DelayHandlerContext handlerContext) {
        if (handlerIterator.hasNext()) {
            DelayMessageHandler<Object> next = handlerIterator.next();
            Object message;
            try {
                message = next.convertMessage(handlerContext);
            } catch (Exception e) {
                // 这个处理器无法处理该消息直接放行下一个执行器
                this.next(handlerContext);
                return;
            }
            try {
                next.execute(handlerContext, message, this);
            } catch (Exception e) {
                log.warn("执行器({})执行错误,消息id:{}", ClassUtil.getClassName(next, true), handlerContext.getMessageId(), e);
            }
        }

    }

}
